const t = require('through2');
const fs = require('fs');
const gulp = require('gulp');
const gutil = require('gulp-util');
const Path = require('path');
const DefaultLoader = require('./loaders/DefaultLoader');
const ZPack = require('./GulpZPack');

let gopt = {
    loaders: {
        '.js': 'JsLoader',
        '.jsx': 'JsLoader',
        '.json': 'JsonLoader',
        '.less': 'LessLoader'
    },
    ext: ['.js', '.jsx', '.json', '.less'],
    host: ''
};

function obtainLoader(loader) {
    if (typeof loader === 'string') {
        return require('./loaders/' + loader);
    } else {
        return loader;
    }
}

function Release(aopt) {
    let opt = Object.assign({}, gopt, aopt);
    let loaders = {};
    for (let i in opt.loaders) {
        loaders[i] = obtainLoader(opt.loaders[i]);
    }
    return t.obj(function(file, enc, cb) {
        if (file.isNull()) {
            cb(null, file);
            return;
        }

        if (file.isStream()) {
            cb(new gutil.PluginError('gulp-zpack', 'Streaming not supported'));
            return;
        }
        let ext = Path.extname(file.path);
        let oldPath = file.relative;
        let loader = loaders[ext] || DefaultLoader;
        let module = {
            file,
            dependency: {},
            realDependency: {}
        };
        let newModule = loader(module, opt);
        if (!(newModule instanceof Promise)) {
            newModule = new Promise(resolve => {
                resolve(newModule);
            });
        }
        newModule.then(newModule => {
            console.log(oldPath, '->', module.file.relative);
            cb(null, newModule.file);
            if (newModule.realDependency) {
                for (var dep of newModule.realDependency) {
                    
                }
            }
        }).catch(err => {
            console.error(err);
            if (opt.avoidError) {
                cb();
            } else {
                cb(new gutil.PluginError(err));
            }
        });

    });
}

module.exports = ZPack;